param ($VersionName   = $(throw 'Must specify version name'),
       $Configuration ='Release'
)

function jp 
{
	$result = $args[0]
	
	for ($i = 1; $i -lt $args.Length; ++$i)
	{
		$result = Join-Path $result $args[$i]
	}
	
	$result
}

$Enlistment = Split-Path -Parent $MyInvocation.MyCommand.Path

$Sln = (jp $Enlistment BGShell.sln)
$Snk = (jp $Enlistment BGShell.snk)
$WFA = (jp $Enlistment WindowsFormsAero.dll)

$BinPath        = (jp $Enlistment BGShell bin $Configuration)

$Exe            = (jp $BinPath BGShell.exe)
$PowerShellDll  = (jp $BinPath BGShell.PowerShell.dll)

$ExeMerged      = (jp $BinPath BGShell-Merged.exe)

$FinalDirectory = (jp $Enlistment     "BGShell-$VersionName")
$FinalZip       = (jp $FinalDirectory "BGShell-$VersionName.zip")
$FinalExe       = (jp $FinalDirectory "BGShell.exe")

$MSBuild  = (jp $Env:SystemRoot Microsoft.NET Framework v3.5 MSBuild.exe)
$ILMerge  = (jp $Enlistment Tools ILMerge ILMerge.exe)
$SevenZip = (jp $Enlistment Tools 7-Zip   7za.exe)

& $MSBuild $Sln /t:Rebuild "/p:Configuration=$Configuration"

if ($LastExitCode)
{
	throw "MSBUILD FAILED: $LastExitCode"
}

& $ILMerge /log /internalize /target:winexe "/keyfile:$Snk" "/attr:$Exe" "/out:$ExeMerged" $Exe $PowerShellDll

if ($LastExitCode)
{
	throw "ILMERGE FAILED: $LastExitCode"
}

if (-not (Test-Path -PathType Container $FinalDirectory))
{
	$null = New-Item -Type Directory -Path $FinalDirectory -ea Stop
}

Copy-Item $ExeMerged $FinalExe       -ea Stop
Copy-Item $WFA       $FinalDirectory -ea Stop

& $SevenZip a -tzip -mx9 $FinalZip $FinalEXE $WFA

if ($LastExitCode)
{
	throw "7-ZIP FAILED: $LastExitCode"
}